/*
 * BanBu_MagicWordsViewController
 * @description 本文件提供对话中魔法文字的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供对话中魔法文字的ViewController
 */


#import "BanBu_MagicWordsViewController.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBuAPIs.h"
#import "BanBu_ImageView.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_NavButton.h"
#import "BanBu_SmileViewAPI.h"
#import "BanBu_ChatViewController.h"
#import "BanBu_MagicWordsAPI.h"
#import "UIImageView+WebCache.h"
#import "BanBu_MagicImageView.h"
#import "SCGIFImageView.h"
#import "BanBu_MagicView.h"
#import "CJSONDeserializer.h"

@interface BanBu_MagicWordsViewController ()
{
    //预览框
    //zyfzyfzyf⬇️
    UIWebView * _preWebview;
    UIImageView * _qipaoView;
    //zyfzyfzyf⬆️

}
@end

@implementation BanBu_MagicWordsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //2014年10月28日10:12:56 by 张毅飞 适配4和4s 以及pad⬇️
    CGFloat height=[UIScreen mainScreen].applicationFrame.size.height;
   
    if (height<500) {
        _inputView.frame=CGRectMake(10,10, 300,50);
        _decorateView.frame=CGRectMake(0, 65, 320, 40);
        _scrollView.frame=CGRectMake(0, 115, 320, 300);
    }
    //2014年10月28日10:12:56 by 张毅飞 适配4和4s 以及pad⬆️
    
    self.title = NSLocalizedString(@"magicWords", nil);
    //zyfzyfzyf⬇️ 初始化预览框
    _preWebview=[[UIWebView alloc]initWithFrame:CGRectMake(67,215,186, 220)];
    [_preWebview.layer setMasksToBounds:YES];
    [_preWebview.layer setCornerRadius:10];
    _preWebview.center=CGPointMake(160, 350);
    [_preWebview setScalesPageToFit:NO];
    // [_preWebview setOpaque:NO];
    _preWebview.hidden=YES;
    
    [_preWebview.layer setCornerRadius:9];
    _preWebview.delegate=self;
    
    _qipaoView=[[UIImageView alloc]initWithFrame:CGRectMake(52, 200, 216, 250)];
    _qipaoView.image = [UIImage imageNamed:@"chat_voice_bubble-right@2x.png"];
    _qipaoView.image = [_qipaoView.image stretchableImageWithLeftCapWidth:30.0 topCapHeight:25.0];
    [self.view addSubview:_qipaoView];
    [self.view addSubview:_preWebview];
    
    _qipaoView.hidden=YES;
    //zyfzyfzyf⬆️

    //创建发送按钮
    [self createSendButton];
    
    _magicWordsView.delegate = self;
    BanBu_ImageView * img = [[BanBu_ImageView alloc]initWithBackGroundImageType:UIImageViewCreatTypeTable];

    self.view.backgroundColor = [UIColor colorWithPatternImage:img.image];
    
    //初始化
    [self setUp];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [_inputView release];
    
    [_resultView release];
    [_magicWordsView release];
    [_bkView release];
    [_smallPictureScrollView release];
    [_bigPictureScrollView release];
    [_decorateButton release];
    [_previewButton release];
    
    [_sendButton release],_sendButton = nil;
    [_pageControl release];
    [_showImageContent release];
    [_showImageView release];
    [_activityIndicator release];
    [_cancelButton release];
    [_addButton release];
    [_tapView release];
    [_decorateView release];
    [_scrollView release];
   
    [super dealloc];
}

//初始化
-(void)setUp
{
    _inputView.text = nil;
    _sendButton.hidden = YES;
    
    _inputView.textColor = [UIColor blackColor];
    _inputView.font = [UIFont systemFontOfSize:18];
    _inputView.layer.borderColor = [[UIColor grayColor] CGColor];
    _inputView.layer.borderWidth = 1.0;
    _inputView.layer.cornerRadius = 4.0;
    _inputView.returnKeyType = UIReturnKeyDefault;
    _inputView.keyboardType = UIKeyboardTypeDefault;
    _inputView.backgroundColor = [UIColor whiteColor];
    _inputView.delegate = self;
    
    self.resultView.frame = self.decorateView.frame;
    self.resultView.layer.cornerRadius = 5.0;
    self.resultView.layer.masksToBounds = YES;

    self.showImageContent.layer.cornerRadius = 5.0;
    
    [self.view addSubview:self.resultView];
    [self.view addSubview:self.decorateView];
    
    _bkView.image = [UIImage imageNamed:@"chat_voice_bubble-right@2x.png"];
    _bkView.image = [_bkView.image stretchableImageWithLeftCapWidth:30.0 topCapHeight:25.0];
    self.resultView.hidden = YES;
    
    [_decorateButton setTitle:NSLocalizedString(@"magicMoreMaterial", nil) forState:UIControlStateNormal];
    [_decorateButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_previewButton setTitle:NSLocalizedString(@"magicPreview", nil) forState:UIControlStateNormal];
    [_previewButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSendButton) name:UITextViewTextDidChangeNotification object:nil];
    
    //初始化装饰素材View
    [self initDecorateView];
    
    [_cancelButton setTitle:NSLocalizedString(@"cancelNotice", nil) forState:UIControlStateNormal];
    [_addButton setTitle:NSLocalizedString(@"addBtn", nil) forState:UIControlStateNormal];
    _showImageContent.center = self.navigationController.view.center;
    [self.view addSubview:_showImageContent];
    _showImageContent.hidden = YES;
    
}

//初始化装饰素材View
-(void)initDecorateView
{
  //  NSDictionary * magicImagePathDic = [NSKeyedUnarchiver unarchiveObjectWithFile:MagicWordsInfoPath];
    NSUserDefaults * def=[NSUserDefaults standardUserDefaults];
    NSDictionary * magicImagePathDic=[def objectForKey:@"magicWords"];
    NSArray * smaleImagePathArray = [magicImagePathDic valueForKey:@"dlist"];
    NSArray * bigImagePathArray = [magicImagePathDic valueForKey:@"jlist"];
    
    int index = 0;
    int page = 0;
    int line = 0;
    _pageControl.numberOfPages = ceilf(smaleImagePathArray.count/20.0);
    
    for (NSDictionary * aMagicDic in smaleImagePathArray)
    {
        BanBu_MagicView * imageView = [[BanBu_MagicView alloc]init];
        
//        BanBu_MagicImageView * imageView = [[BanBu_MagicImageView alloc]init];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.userInteractionEnabled = YES;
        
//        CGRect frame = CGRectMake(page*320 + (index%5)*62 + 10, (index/5)*52 + (index/5)*6, 52, 52);
//        if (frame.origin.y<0)
//        {
//            frame.origin.y = 0;
//        }
        CGRect frame=CGRectMake((10+62*index)+320*page, line*59, 52, 52);
        imageView.frame = frame;
        
        [imageView setImageViewFrame:YES];
        
        imageView.imageView.idStr = [aMagicDic valueForKey:@"id"];
        imageView.imageView.bigUrl = [aMagicDic valueForKey:@"full"];
        
        //添加点击事件
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnAction:)
        ];
        [imageView addGestureRecognizer:tap];
        [tap release];
        
        NSString * imageUrl = [aMagicDic valueForKey:@"file"];
    
        [imageView.imageView setImageWithUrlString:imageUrl withFolderName:MagicWordsFolder];
        
        [_smallPictureScrollView addSubview:imageView];
        [imageView release];
        index ++;
        if (index%5==0&&index!=0) {
            index=0;
            ++line;
        }
        if (line%5==0&&line!=0) {
            ++page;
            line=0;
        }
    }
    CGSize smallSize=CGSizeMake(320*(smaleImagePathArray.count/25+(smaleImagePathArray.count%25?1:0)), _smallPictureScrollView.frame.size.height);
    _smallPictureScrollView.contentSize=smallSize;
    _smallPictureScrollView.pagingEnabled=YES;
    _smallPictureScrollView.showsHorizontalScrollIndicator=NO;
    _smallPictureScrollView.delegate=self;

    
    index = 0;
    //page = 0;
    for (NSDictionary * aMagicDic in bigImagePathArray)
    {
        BanBu_MagicView * imageView = [[BanBu_MagicView alloc]init];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.userInteractionEnabled = YES;
        
        CGRect frame = CGRectMake(page*320 + (index%5)*60 + 10, 7, 50, 50);
        imageView.frame = frame;
        [imageView setImageViewFrame:NO];
        
        imageView.imageView.idStr = [aMagicDic valueForKey:@"id"];
        imageView.imageView.bigUrl = [aMagicDic valueForKey:@"full"];
        
        //添加点击事件
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnAction:)
                                        ];
        [imageView addGestureRecognizer:tap];
        [tap release];
        
        NSString * imageUrl = [aMagicDic valueForKey:@"file"];
        
        [imageView.imageView setImageWithUrlString:imageUrl withFolderName:MagicWordsFolder];
        
        [_bigPictureScrollView addSubview:imageView];
        [imageView release];
        
        index ++;
        page = index/20;
    }
    _bigPictureScrollView.hidden=YES;
}

//创建发送按钮
-(void)createSendButton
{
    //添加“删除”按钮
    CGFloat btnLen1 = [NSLocalizedString(@"sendReply", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
    
    self.sendButton = [[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal] autorelease];
    _sendButton.position = ButtonPositionRight;
    _sendButton.frame=CGRectMake(0, 0,btnLen1+20, 30);
    _sendButton.tag = 101;
    [_sendButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
    [_sendButton setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
    
    UIBarButtonItem *sendItem = [[[UIBarButtonItem alloc] initWithCustomView:_sendButton] autorelease];
    sendItem.enabled = YES;
    self.navigationItem.rightBarButtonItem = sendItem;
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    self.tapView.hidden = NO;
    [self.view bringSubviewToFront:self.tapView];
}

//更改发送按钮显示状态
-(void)changeSendButton
{
    if (_inputView.text.length)
    {
        _sendButton.hidden = NO;
    }
    else
    {
        _sendButton.hidden = YES;
    }
}

//关闭键盘
- (IBAction)setKeyboardDown:(UIControl *)sender
{
    [_inputView resignFirstResponder];
}

//发消息
-(void)sendAction:(UIButton *)sender
{
    //校验是否为空
    if (![self trimBlankString:_inputView.text].length)
    {
        [self.navigationController popToViewController:self.appChatController animated:YES];
        
        return;
    }
    
    if (!self.downloadCorrect)
    {
        if (![self trimBlankString:_inputView.text].length)
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"nilNotice", nil) activityAnimated:NO duration:1.3f];
            return;
        }
        //提交预览
        [self previewAction:_previewButton];
        //return;
    }
    
    UIActionSheet * sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ice_actionSheetButtionTitle", nil), nil];
    
    [sheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        //发完消息后 返回对话
        NSMutableDictionary * sendDic = [NSMutableDictionary dictionaryWithCapacity:8];
        [sendDic setValue:_contentStr forKey:KeyContent];
        [sendDic setValue:[NSNumber numberWithInt:ChatCellTypeSpecialText] forKey:KeyType];
        [sendDic setValue:@"magicWords" forKey:KeyShowFrom];
        [sendDic setValue:@"toMagicWords" forKey:KeyLinkTo];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kSendMsgAllTypeNotification object:sendDic];
    }
    [self.navigationController popViewControllerAnimated:YES];

}

//去掉空格、空行
-(NSString *)trimBlankString:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    return string;
}

#pragma mark - 素材

//显示装饰素材
- (IBAction)decorattingAction:(UIButton *)sender
{
    [_inputView resignFirstResponder];
    _scrollView.hidden=NO;
    
    //zyfzyfzyf⬇️
    _preWebview.hidden=YES;
    _qipaoView.hidden=YES;
    //zyfzyfzyf⬆️
//2014年10月27日16:58:30 by 张毅飞 隐藏发送按钮
    _sendButton.hidden=YES;
    _sendButton.enabled=NO;
}

//检查能否添加大图
-(BOOL)checkAddBig
{
    NSString * text = _inputView.text;
    NSString * searchStr = @"[d.";
    
    BOOL returnBl = NO;
    
    if ([text rangeOfString:searchStr].location == NSNotFound)
    {
        //没有选择大图，可以选择
        returnBl = YES;
    }
    else
    {
        returnBl = NO;
    }
    return returnBl;
}

-(void)btnAction:(UITapGestureRecognizer *)tap
{
    _showImageContent.hidden = YES;
    BanBu_MagicView * imageView = (BanBu_MagicView *)tap.view;
    
    NSString * bigUrl = imageView.imageView.bigUrl;
    
    _selectedIdStr = imageView.imageView.idStr;
    
    NSString * imagePath = [AppComManager pathForMagicWordsImage:bigUrl];
    
    if ([FileManager fileExistsAtPath:imagePath])
    {
        [self.activityIndicator stopAnimating];
        self.activityIndicator.hidden = YES;
    }
    else
    {
        [self.activityIndicator stopAnimating];
        self.activityIndicator.hidden = YES;
    }
    //2014年10月28日10:21:17 by 张毅飞 输入框自动滚屏⬇️
    NSMutableString * textStr=[NSMutableString stringWithString:_inputView.text];
    [textStr insertString:[NSString stringWithFormat:@"[%@]",_selectedIdStr] atIndex:_inputView.selectedRange.location];
    _inputView.text = [NSString stringWithFormat:@"%@",textStr];
    
    if (_inputView.contentOffset.y+_inputView.frame.size.height<=_inputView.contentSize.height) {
        _inputView.contentOffset=CGPointMake(0, _inputView.contentSize.height-_inputView.frame.size.height);
    }
    //自动滚屏⬆️

    //去下载大图
  //  [_showImageView setImageWithUrlString:bigUrl withFolderName:MagicWordsFolder];
}

//取消
- (IBAction)cancelButton:(UIButton *)sender
{
    _showImageView.gifFile = nil;
    _showImageContent.hidden = YES;
}

//添加
- (IBAction)addButton:(UIButton *)sender
{
    _showImageView.gifFile = nil;
    _showImageContent.hidden = YES;
 
    if ([_selectedIdStr rangeOfString:@"d."].location == NSNotFound)
    {
        NSString * prefixText = [_inputView.text substringToIndex:_inputView.selectedRange.location];
        
        NSString * suffixText = [_inputView.text substringFromIndex:_inputView.selectedRange.length+_inputView.selectedRange.location];
        
        NSString * wholeText = [NSString stringWithFormat:@"%@[%@]%@",prefixText,_selectedIdStr,suffixText];
        
        _inputView.text = wholeText;
    }
    else
    {
        BOOL bl = [self checkAddBig];
        if (bl)
        {
            _inputView.text = [NSString stringWithFormat:@"%@[%@]",_inputView.text,_selectedIdStr];
        }
        else
        {
            /*
            NSInteger location = [_inputView.text rangeOfString:@"[d."].location;
            NSString * text = [_inputView.text substringToIndex:location];
            NSLog(@"text:%@",text);
            _inputView.text = [NSString stringWithFormat:@"%@[%@]",text,_selectedIdStr];
             */
            _inputView.text = [NSString stringWithFormat:@"%@[%@]",_inputView.text,_selectedIdStr];

        }
    }
}

#pragma mark -
#pragma mark -  ScrollViewDelagate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageControl.currentPage = scrollView.contentOffset.x/320.0;
}

#pragma  mark - 预览
//显示预览
- (IBAction)previewAction:(UIButton *)sender
{
    [_inputView resignFirstResponder];
    
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
    self.navigationController.view.userInteractionEnabled = NO;
    
    NSMutableDictionary * pardic = [NSMutableDictionary dictionaryWithCapacity:8];
    [pardic setValue:_inputView.text forKey:KeyMagicText];
    
    [AppComManager getMagicWordsHtml:BanBu_Make_MagicChatHtml par:pardic delegate:self];
    
    _scrollView.hidden=YES;
    self.resultView.hidden = NO;
    _bkView.hidden = YES;
    _magicWordsView.hidden = YES;
    
    //2014年10月27日16:57:21 by 张毅飞 发送按钮显示
    _sendButton.hidden=NO;
    _sendButton.enabled=YES;
    //zyfzyfzyf⬇️
    
    // self.resultView.hidden = NO;
    //  _bkView.hidden = YES;
    //  _magicWordsView.hidden = YES;
    //zyfzyfzyf⬆️

}

//设置预览的内容
-(void)setContent:(NSString *)content
{
    _bkView.hidden = NO;
    _magicWordsView.hidden = NO;
    
    NSData * data = [NSData dataFromBase64String:content];
    
    //解析content；
    content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    self.contentStr = content;
    
    
    
    NSURL * baseUrl = [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]];
    [_preWebview loadHTMLString:_contentStr baseURL:baseUrl];
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
    

}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    _preWebview.hidden=NO;
    _qipaoView.hidden=NO;
    //zyfzyfzyf⬇️
    CGRect frame = webView.frame;
    frame.size.height = 1;
    webView.frame = frame;
    
    CGSize fittingSize=[webView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    CGRect frame2=CGRectZero;
    frame2.size.height=frame.size.height+30;
    frame2.size.width=frame.size.width+30;
    
    //2014年10月28日10:18:59 by 张毅飞 适配iPhone4，4S，pad⬇️
    CGFloat screenHei=[UIScreen mainScreen].applicationFrame.size.height;
    if (screenHei <500) {
        
        if (fittingSize.height<=250) {
            _preWebview.frame=frame;
            _qipaoView.frame=frame2;
            webView.center=CGPointMake(160, 220);
            _qipaoView.center=CGPointMake(160, 220);
        }
        else
        {
            _preWebview.frame=CGRectMake(67,125,186, 220);
            _qipaoView.frame=CGRectMake(52, 110, 216, 250);
        }
        
    }
    else
    {
        if (fittingSize.height<=250) {
            _preWebview.frame=frame;
            _qipaoView.frame=frame2;
            webView.center=CGPointMake(160, 320);
            _qipaoView.center=CGPointMake(160, 320);
        }
        else
        {
            _preWebview.frame=CGRectMake(67,215,186, 220);
            _qipaoView.frame=CGRectMake(52, 200, 216, 250);
        }
        
    }
    //2014年10月28日10:18:59 by 张毅飞 适配iPhone4，4S，pad⬆️
    NSUserDefaults *defHeight=[NSUserDefaults standardUserDefaults];
    [defHeight setObject:[NSString stringWithFormat:@"%f",fittingSize.height+50] forKey:KeyHeight];
    [defHeight synchronize];
    
    //国外webView内存泄露解决办法，不知道真的假的
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
    //zyfzyfzyf⬆️

    }

#pragma mark- BanBuRequestDelegate
-(void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    self.navigationController.view.userInteractionEnabled = YES;
    
    if (error)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:1.3f];
    }
    
    if ([[resDic valueForKey:@"ok"] boolValue])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            //显示
            [self setContent:[resDic valueForKey:@"magictext"]];
        });
    }
}

- (IBAction)hiddenOrView:(UIControl *)sender
{
    self.tapView.hidden = YES;
    [_inputView resignFirstResponder];
}

@end
